import { defineStore } from 'pinia'
import { authAPI, userAPI } from '@/api/user'
import router from '@/router'
import {persistStorage} from "@/stores/index.js";

export const useUserStore = defineStore('user', {
    state: () => ({
        token:'',
        userInfo: null,
        permissions: [],
        roles: [],
        tenantId:'',
        userId:'',  // 移除了前面的 - 符号
        asyncRoutesAdded: false,
        asyncRoutes: [],
        menuTree: [],
        navItems: [],
        activeMenuTree:[],
        activeNav: '',
        tenantName:''
    }),
    fetchPermissions: async () => {
        try {
            const { data } = await userAPI.getPermissions();
            return data.tree;
        } catch (error) {
            console.error('获取权限数据失败:', error);
            throw error;
        }
    },
    // 新增持久化配置
    persist: {
        enabled: true,      // 启用持久化
        exclude: ['asyncRoutesAdded'] // 排除不需要持久化的字段
    },

    getters: {
        isLoggedIn: (state) => !!state.token,
        hasPermission: (state) => (requiredPermissions) => {
            if (!requiredPermissions) return true
            const perms = Array.isArray(requiredPermissions)
                ? requiredPermissions
                : [requiredPermissions]
            return state.permissions.some(p => perms.includes(p))
        }
    },

    actions: {
        async login(loginData) {
            try {
                this.tenantId = loginData.tenantId
                this.tenantName = loginData.tenantName
                const {data} = await authAPI.login(loginData)
                console.log(data)
                this.token = data.tokenValue
                this.userId = data.userId
                await this.getUserInfo()
                return Promise.resolve()
            } catch (error) {
                this.logout()
                return Promise.reject(error)
            }
        },

        async getUserInfo() {
            if (!this.token) return
            try {
                const {data} = await userAPI.getInfo(this.userId)
                this.userInfo = data.user
                this.permissions = data.permissions
                this.roles = data.roles
                this.menuTree = data.menuTree
                data.menuTree.forEach(item => {
                    if (item.menu.menuType === 'NAV') {
                       this.navItems.push(item.menu)
                    }
                })
                if(this.navItems.length){
                   this.activeMenuTree = data.menuTree[0].children
                } else {
                    this.activeMenuTree = data.menuTree
                }
            } catch (error) {
                console.error('获取用户信息失败:', error)
              //  this.logout()
            }
        },

        async logout() {
            try {
                await authAPI.logout();
            } finally {
                await persistStorage.dropInstance();
                this.$reset();
                router.replace('/login');
            }
        },
        // 新增方法示例：更新用户信息
        async updateUser(userData) {
            try {
                const { data } = await userAPI.update(userData)
                this.userInfo = { ...this.userInfo, ...data }
                return Promise.resolve(data)
            } catch (error) {
                return Promise.reject(error)
            }
        },
        toggleNav(id){
            this.activeNav = id
            this.menuTree.forEach(item => {
                if(item.menu.id === id){
                    this.activeMenuTree = item.children
                }
            })
        }


    }
})